<template>
  <div class="tablePageWarp">
    <div class="commonSelectWidth table-page-search-wrapper" style="margin-bottom: 0;">
      <a-form layout="vertical" >
      <a-row :gutter="[16,5]">
        <a-col :md="24" :sm="24" :lg="6">
          <a-form-model-item label="任务名称">
            <a-input v-model="queryParams.name" :placeholder="$t('pleaseInput')" @keyup.enter="refreshData(true)" allowClear/>
          </a-form-model-item>
        </a-col>
        <a-col :md="24" :sm="24" :lg="6">
          <a-form-model-item label="任务状态" style="padding:0">
            <a-select
              mode="multiple"
              :maxTagCount="1"
              allow-clear
              v-model="queryParams.status"
              @change="refreshData(true)"
              :placeholder="$t('pleaseSelect')"
            >
              <a-select-option v-for="(item, index) in taskUpdateDictCode" :key="index" :value="item.value">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="24" :sm="24" :lg="6">
          <a-form-model-item label="创建人">
            <a-select
              v-model="queryParams.createBy"
              showSearch
              allow-clear
              optionFilterProp="children"
              @change="refreshData(true)"
              :filterOption="$commonFun.filterOption"
              :placeholder="$t('pleaseSelect')"
              :maxTagCount="1"
              style="width:100%"
            >
              <a-select-option
                v-for="(item,index) in userList"
                :key="'user'+index"
                :value="item.id"
                :title="item.name"
              >
                {{ item.name + '('+item.account+')' }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="24" :sm="24" :lg="6">
          <a-form-model-item label="创建时间">
            <a-range-picker
              @change="selectDateRange"
              v-model="createTime"
              :show-time="{
                hideDisabledOptions: true,
                defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
              }"
              style="width: 100%"
              :placeholder="['创建时间-开始','结束']"
            />
          </a-form-model-item>
        </a-col>
        <a-col :md="24" :sm="24" :lg="6">
          <a-form-model-item label="车型代码">
            <car-model-select
              mode="default"
              :query="{ time:new Date(), selectAll: false}"
              :has-all="false"
              :clear="true"
              v-model="queryParams.modelId"
              @change="refreshData(true)"
              style="width:100%;margin-bottom:0px"
            />
          </a-form-model-item>
        </a-col>
        <a-col :md="24" :sm="24" :lg="6">
          <a-form-model-item :label="$t('smartDrivingDomainVersion')">
            <a-input v-model="queryParams.vehicleVersion" :placeholder="$t('pleaseInput')" @keyup.enter="refreshData(true)" allowClear/>
          </a-form-model-item>
        </a-col>
        <a-col :md="14" :sm="24" :lg="10" style="margin-top:22px">
          <div class="searchBtns">
            <a-button-group>
              <auth-button type="primary" :auth="taskPerms[testType].view" @click="refreshData(true)">
                <i class="iconfont icon-chazhao"></i>
                {{ $t('inquiry') }}
              </auth-button>
              <a-button @click="clearQuery">
                <i class="iconfont icon-qingkong"></i>
                {{ $t('clear') }}
              </a-button>
            </a-button-group>
            <auth-button :auth="taskPerms[testType].add" @click="create" >
              <i class="iconfont icon-xinjian"></i>
              {{ $t('new') }}
            </auth-button>
          </div>
        </a-col>
      </a-row>
      </a-form>
    </div>
    <s-table
      ref="table"
      class="h100 withMinHeightTbodyBox"
      :rowKey="(record, index) => record.id +'-' + index"
      :columns="columns"
      :data="loadData"
      :getPopupContainer="$commonFun.getPopupContainer"
    >
      <!-- 名称 -->
      <template slot="task" slot-scope="text, record">
        <a @click="lookupTest(record)"><table-ellipsis :text="text"/></a>
      </template>
      <!-- 升级策略 -->
      <template slot="strategyName" slot-scope="text, record">
        <a @click="showStrategy(record.strategyId)"><table-ellipsis :text="text"/></a>
      </template>
      <!-- 任务状态 -->
      <template slot="status" slot-scope="text, record">
        <table-ellipsis :text="$store.getters.getDictCodeObj('taskUpdateDictCode')[record.status] || '-'"/>
      </template>
      <template slot="expirationDate" slot-scope="text, record">
        <div v-if="record.type==9||record.type==10">
          永久
        </div>
        <div v-else-if="!record.endTime">-</div>
        <a-tooltip
          v-else
          :title="moment(record.startTime).format('YYYY-MM-DD HH:mm:SS') + ' 至 ' + moment(record.endTime).format('YYYY-MM-DD HH:mm:ss')">
          {{durationHumanize(record)}}
        </a-tooltip>
      </template>
      <template slot="upgradeVehicle" slot-scope="text, record">
        <div style="position: relative">
          <table-ellipsis
            style="width: 30%"
            :text="`${record.successVehicle || 0}/${record.totalVehicle || 0}`"
          />
          <a-progress
            :percent="(record.successVehicle || 0 / record.totalVehicle || 0) * 100"
            size="small"
            :show-info="false"
            style="width: 70%; position: absolute; right: 0; top: 0"
          />
        </div>
      </template>
      <template slot="operation" slot-scope="text, record">
        <template>
          <auth-button class="set-margin" @click="lookupTest(record)" type="primary" :ghost="true" size="small"><i class="iconfont icon-yanjing"/>{{ $t('view') }}</auth-button>
          <auth-button class="set-margin" @click="create(record.id)" type="primary" :ghost="true" size="small"><i class="iconfont icon-fuzhi"/>{{ $t('copy') }}</auth-button>
          <auth-button :disabled="record.status == 16 || record.status == 17 || record.status == 18" @click="handelCancel(record)" style="word-break: keep-all;" type="danger" :ghost="true" size="small"><a-icon type="close" />{{ $t('cancel') }}</auth-button>
        </template>
      </template>
    </s-table>
    <!-- 查看策略 -->
    <show-condition-update-strategy
      ref="showStrategy"
      :updataStrategyId="strategyId"
    ></show-condition-update-strategy>
  </div>
</template>

<script>
  import detailItem from '@comp/EditItem'
  import { mapState, mapMutations } from "vuex";
  import userApi from "@api/modules/system/user";
  import moment from 'moment'
  import CarModelSelect from '@/views/components/CarModelSelect'
  import {taskPerms, testTaskPerms} from '@/config/permission/index'
  import AuthButton from '@/components/AuthButton'
  import {STable} from '@/components'
  import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
  import { developColumn, channelColumn, warehouseColumn } from "@views/task/test/list";
  import EditTestForm from "@views/strategy/FotaUpdate/components/EditTestForm";
  import EditChannelTest from "@views/strategy/FotaUpdate/components/EditChannelTest";
  import {minxinDrawerUse, minxinGetDomHeight} from "@/utils/mixin";
  import taskApi from "@api/modules/task";
  import LookupTestForm from "@views/strategy/FotaUpdate/components/LookupTestForm";
  import ShowConditionUpdateStrategy from '@/views/components/ShowConditionUpdateStrategy'
  import {taskBase} from "@views/task/components/MinNewTaskBase";
  import DetailTask from "@views/components/DetailTask";


  export default {
    components: {
      detailItem, CarModelSelect, AuthButton, STable, tableEllipsis, LookupTestForm, ShowConditionUpdateStrategy
    },
    name: 'warehouseTaskList',
    mixins: [minxinDrawerUse, taskBase],
    computed: {
      ...mapState({
        taskUpdateDictCode: (state) => state.dict.taskUpdateDictCode,
        taskVehicleQueryParams: (state) => state.strategy.taskVehicleQueryParams,
        newTaskDataAll: (state) => state.newTask.newTaskData
      }),
      newTaskData(){
        return this.newTaskDataAll[this.upgradeTriggerType];
      },
    },
    data() {
      return {
        moment,
        taskPerms,
        queryParams: {
        },
        upgradeTriggerType : 'warehouse',
        userList: [],
        tableData: [],
        createTime: null,
        testType: 'warehouse',
        columns: '',
        strategyId: null
      }
    },
    created() {
      this.columns = warehouseColumn
    },
    mounted() {
      this.getUsers();
      this.$store.dispatch('getTaskUpdateDictCodeData');
    },
    methods: {
      ...mapMutations([
        'RESET_NEWTASK_DATA'  
      ]),
      getUsers() {
        userApi.getUserPageData({pageSize: 5000}).then(res => {
          this.userList = res.data;
        }).catch((e) => vm.$message.error("获取创建人信息失败！"))
      },
      selectDateRange(date, dateString) {
        this.queryParams.createTimeGte = dateString[0]
        this.queryParams.createTimeLte = dateString[1]
        this.refreshData(true);
      },
      loadData(parameter) {
        const vm = this
        // 如果是全部则不传值给后端
        const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParams))
        // eslint-disable-next-line no-restricted-syntax
        for (const key in JnqueryParam) {
          if (JnqueryParam[key] === '') {
            JnqueryParam[key] = undefined
          }
        }
        this.tableData = [];
        // JnqueryParam.type = [8, 9, 10];
        var apiPromise = vm.$api
          .getWarehouseTaskPageData({...parameter, ...JnqueryParam});
        return new Promise((resolve, reject) => {
          return apiPromise.then((res) => {
            if (res.data) {
              this.tableData = res.data;
            }
            resolve(res);
          }).catch(e => reject(e));
        });
      },
      getCheckboxProps(record) {
        return {
          props: {
            disabled: record.status === 16 || record.status === 17 || record.status === 18, // Column configuration not to be checked
            name: record.id,
          },
        }
      },
      refreshData(isToFirstPage = true) {
        const vm = this
        vm.$nextTick(() => {
          this.$refs.table.refresh(isToFirstPage)
        })
      },
      durationHumanize(record) {
        let cur = new Date().getTime();
        let s = moment.duration(record.endTime - record.startTime).humanize();
        let remain = Math.max(0, record.endTime - Math.max(cur, record.startTime));
        if (remain > 0) {
          s += '，剩余 ' + moment.duration(remain).humanize();
        }
        return s;
      },
      clearQuery() {
        this.queryParams = {
        }
        this.createTime = undefined;
        this.refreshData(true)
      },
// 新建测试
      create(copyId) {
        const vm = this
        // vm.SET_UPGRADE_TRIGGER_TYPE(this.upgradeTriggerType)
        vm.$store.commit('RESET_NEWTASK_DATA', this.upgradeTriggerType)
        // vm.RESET_NEWTASK_DATA() // 新建时先清除缓存
        vm.newTaskData.copyId = copyId
        vm.getCurrentStepConfig(vm.stepNum)
        vm.toggleDrawerMain(true)
        // vm.setDefaultName()
        // 清除第三个任务审核审批用户设置数据
        sessionStorage.removeItem('nodeOfApprovalObj')
      },
      // 查看测试弹框
      lookupTest (record) {
        const buttons = []
        // this.SET_UPGRADE_TRIGGER_TYPE(this.upgradeTriggerType)
        this.showRightDrawer(DetailTask, record.name, buttons, 'huge', {
          taskId: record.id,
          type: record.type,
          taskStatus: record.status,
          upgradeTriggerType:this.upgradeTriggerType,
          channel: 1
        })
      },
      // 查看策略
      showStrategy (strategyId) {
        this.strategyId = strategyId
        this.$refs.showStrategy.visible = true
      },
      handelCancel (record) {
        const vm = this
        this.$confirm({
          title: vm.$t('cancelTask'),
          content: vm.$t('newCancelTaskTip').replace('__TaskName__', record.name),
          class: 'confirmStyle',
          width: 378,
          onOk () {
            vm.$api.cancelTask({ ids: [record.id] }, vm.testType).then(() => {
              vm.$message.success(vm.$t('successfullyOperation'))
              vm.refreshData(true)
            })
          },
          onCancel () { }
        })
      },


    }
  }
</script>
<style lang="less" scoped>
.set-margin {
  margin-right: 12px;
}
::v-deep .ant-form-item-label {
  padding-bottom: 2px;
}
::v-deep .ant-form-item {
  margin-bottom: 0;
}
</style>